'use client';

import React, { createContext, useContext, useReducer, useEffect, useCallback } from 'react';
import { 
  UserProfile, 
  Recommendation, 
  UserSchedule, 
  Conflict, 
  AppState, 
  AppStep 
} from '@/types';

// 状态管理Action类型
type AppAction = 
  | { type: 'SET_STEP'; payload: AppStep }
  | { type: 'SET_USER_PROFILE'; payload: UserProfile }
  | { type: 'SET_RECOMMENDATIONS'; payload: Recommendation[] }
  | { type: 'SET_USER_SCHEDULE'; payload: UserSchedule }
  | { type: 'SET_CONFLICTS'; payload: Conflict[] }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | undefined }
  | { type: 'RESET_STATE' };

// 初始状态
const initialState: AppState = {
  currentStep: 'welcome',
  recommendations: [],
  conflicts: [],
  loading: false,
};

// Reducer函数
const appReducer = (state: AppState, action: AppAction): AppState => {
  switch (action.type) {
    case 'SET_STEP':
      return { ...state, currentStep: action.payload };
    case 'SET_USER_PROFILE':
      return { ...state, userProfile: action.payload };
    case 'SET_RECOMMENDATIONS':
      return { ...state, recommendations: action.payload };
    case 'SET_USER_SCHEDULE':
      return { ...state, userSchedule: action.payload };
    case 'SET_CONFLICTS':
      return { ...state, conflicts: action.payload };
    case 'SET_LOADING':
      return { ...state, loading: action.payload };
    case 'SET_ERROR':
      return { ...state, error: action.payload };
    case 'RESET_STATE':
      return initialState;
    default:
      return state;
  }
};

// Context类型
interface AppContextType {
  state: AppState;
  dispatch: React.Dispatch<AppAction>;
  // 便捷方法
  setStep: (step: AppStep) => void;
  setUserProfile: (profile: UserProfile) => void;
  setRecommendations: (recommendations: Recommendation[]) => void;
  setUserSchedule: (schedule: UserSchedule) => void;
  setConflicts: (conflicts: Conflict[]) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | undefined) => void;
  resetState: () => void;
}

// 创建Context
const AppContext = createContext<AppContextType | undefined>(undefined);

// Provider组件
interface AppProviderProps {
  children: React.ReactNode;
}

export const AppProvider: React.FC<AppProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(appReducer, initialState);

  // 从localStorage恢复状态
  useEffect(() => {
    const savedProfile = localStorage.getItem('yunqi-user-profile');
    const savedSchedule = localStorage.getItem('yunqi-user-schedule');
    
    if (savedProfile) {
      try {
        const profile = JSON.parse(savedProfile);
        dispatch({ type: 'SET_USER_PROFILE', payload: profile });
      } catch (error) {
        console.error('Failed to parse saved profile:', error);
      }
    }
    
    if (savedSchedule) {
      try {
        const schedule = JSON.parse(savedSchedule);
        dispatch({ type: 'SET_USER_SCHEDULE', payload: schedule });
      } catch (error) {
        console.error('Failed to parse saved schedule:', error);
      }
    }
  }, []);

  // 保存用户画像到localStorage
  useEffect(() => {
    if (state.userProfile) {
      localStorage.setItem('yunqi-user-profile', JSON.stringify(state.userProfile));
    }
  }, [state.userProfile]);

  // 保存用户日程到localStorage
  useEffect(() => {
    if (state.userSchedule) {
      localStorage.setItem('yunqi-user-schedule', JSON.stringify(state.userSchedule));
    }
  }, [state.userSchedule]);

  // 便捷方法
  const setStep = useCallback((step: AppStep) => dispatch({ type: 'SET_STEP', payload: step }), []);
  const setUserProfile = useCallback((profile: UserProfile) => dispatch({ type: 'SET_USER_PROFILE', payload: profile }), []);
  const setRecommendations = useCallback((recommendations: Recommendation[]) => 
    dispatch({ type: 'SET_RECOMMENDATIONS', payload: recommendations }), []);
  const setUserSchedule = useCallback((schedule: UserSchedule) => 
    dispatch({ type: 'SET_USER_SCHEDULE', payload: schedule }), []);
  const setConflicts = useCallback((conflicts: Conflict[]) => 
    dispatch({ type: 'SET_CONFLICTS', payload: conflicts }), []);
  const setLoading = useCallback((loading: boolean) => dispatch({ type: 'SET_LOADING', payload: loading }), []);
  const setError = useCallback((error: string | undefined) => dispatch({ type: 'SET_ERROR', payload: error }), []);
  const resetState = useCallback(() => {
    localStorage.removeItem('yunqi-user-profile');
    localStorage.removeItem('yunqi-user-schedule');
    dispatch({ type: 'RESET_STATE' });
  }, []);

  const value: AppContextType = {
    state,
    dispatch,
    setStep,
    setUserProfile,
    setRecommendations,
    setUserSchedule,
    setConflicts,
    setLoading,
    setError,
    resetState,
  };

  return (
    <AppContext.Provider value={value}>
      {children}
    </AppContext.Provider>
  );
};

// Hook for using app context
export const useApp = (): AppContextType => {
  const context = useContext(AppContext);
  if (!context) {
    throw new Error('useApp must be used within AppProvider');
  }
  return context;
};